<template>
  <div>
    <el-row :gutter="15" class="mb8">
      <el-col :span="1.5">
        <el-button
          icon="el-icon-plus"
          plain
          size="mini"
          @click="authorizedDevice"
          v-hasPermi="['maintenance:device:add']"
          >授权设备
        </el-button>
      </el-col>
      <el-form
        :model="queryParams"
        ref="queryParamsRef"
        label-width="70px"
        @submit.prevent
        inline
        class="el-form-search"
      >
        <!--设备名称-->
        <el-form-item
          label="设备名称"
          prop="devName"
          class="el-form-search-item"
        >
          <el-input
            clearable
            placeholder="设备名称"
            v-model.trim="queryParams.devName"
          ></el-input>
        </el-form-item>

        <!-- 下拉框 -->
        <el-form-item
          label="变电站"
          prop="substationNum"
          class="el-form-search-item"
        >
          <el-select
            clearable
            placeholder="变电站"
            filterable
            v-model="queryParams.substationNum"
          >
            <el-option
              v-for="item in substationOptions"
              :key="item.num"
              :value="item.num"
              :label="item.substationName"
            ></el-option>
          </el-select>
        </el-form-item>

        <!-- 设备状态 -->
        <el-form-item
          label="设备状态"
          prop="devStatus"
          class="el-form-search-item"
        >
          <el-select
            clearable
            placeholder="设备状态"
            v-model="queryParams.devStatus"
          >
            <el-option
              v-for="dict in devStatusOptions"
              :key="dict.num"
              :value="dict.code"
              :label="dict.name"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item class="el-form-search-item">
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-search"
            @click="handleQuery"
            >搜索</el-button
          >
          <el-button size="mini" icon="el-icon-refresh" @click="handleRefresh"
            >重置</el-button
          >
        </el-form-item>
      </el-form>
    </el-row>
    <el-table
      ref="deiveAuthorize"
      @row-click="handleRowClick"
      :data="deviceList"
      :height="tableHeight"
      v-loading="loading"
      border
      stripe
      @expand-change="handleExpandChange"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="40" />
      <el-table-column
        align="center"
        label="#"
        type="index"
        width="50"
        :resizable="false"
      >
        <template slot-scope="scope">
          <span>{{
            (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="设备名称"
        prop="devName"
        :resizable="false"
        show-overflow-tooltip
        width="150"
      ></el-table-column>
      <el-table-column
        align="center"
        label="设备编号"
        prop="devNum"
        :resizable="false"
        show-overflow-tooltip
        width="120"
      ></el-table-column>
      <el-table-column
        align="center"
        label="所属地区"
        prop="substation.ancestorNames"
        :resizable="false"
      ></el-table-column>
      <el-table-column
        align="center"
        label="所属变电站"
        prop="substation.substationName"
        :resizable="false"
      ></el-table-column>
    </el-table>

    <!-- 分页控件 -->
    <pagination
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog title="授权" :visible.sync="authorizeOpen">
      <el-table :data="authorizedDeviceList" v-loading="loading" border>
        <el-table-column
          align="center"
          prop="devName"
          label="设备名称"
        ></el-table-column>
        <el-table-column
          align="center"
          prop="devNum"
          label="设备编号"
        ></el-table-column>
        <el-table-column
          align="center"
          prop="devModelNum"
          label="设备型号"
        ></el-table-column>
        <el-table-column
          align="center"
          label="设备状态"
          prop="deviceStatus.name"
          width="80"
          :resizable="false"
        >
          <template slot-scope="scope">
            <el-tag :type="statusFormat(scope.row.devStatus)">{{
              scope.row.deviceStatus.name
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="是否授权"
          prop="authorizeStatus"
          width="80"
          :resizable="false"
        >
          <template slot-scope="scope">
            <el-tag
              :type="scope.row.authorizeStatus === 1 ? 'success' : 'danger'"
              >{{
                scope.row.authorizeStatus === 1 ? "已授权" : "未授权"
              }}</el-tag
            >
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="130">
          <template slot-scope="scope">
            <el-button
              type="text"
              v-if="
                userInfo.userName !== scope.row.createBy &&
                scope.row.authorizeStatus == 1
              "
              @click="cancelAuthorize(scope.row)"
              >取消授权</el-button
            >
            <el-button
              type="text"
              @click="handleDeleteAuthorize(scope.row, scope.$index)"
              >移除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAuthorizedForm"
          >确认授权</el-button
        >
        <el-button @click="authorizeOpen = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  getDeviceListFold,
  getDeviceList,
  addDevice,
  getByNum,
  editDevice,
  removeBatch,
  getDeviceSortList,
} from "@/api/device/device";
import {
  addDeviceAuthorized,
  listDeviceAuthorized,
  cancelAuthorized,
} from "@/api/authorization/deviceAuthorized";
import { getDeviceStatus } from "@/api/maintenance/dimensionTables";

import { listSubstation } from "@/api/maintenance/substation";

export default {
  data() {
    return {
      authorizedDeviceList: [],
      deviceList: [],
      authorizeOpen: false,
      substationOptions: [],
      userList: [],
      devStatusOptions: [],
      total: 0,
      loading: false,
      tableHeight: "calc(100vh - 350px)", // 遮罩层
      authorizeForm: {
        userId: "",
      }, //

      // 搜索框
      queryParams: {
        pageNum: 1,
        pageSize: 30,
        devStatus: "",
        substationNum: "",
        devName: "",
        // orderByColumn: "update_time",
        // isAsc: "ASC",
      },
    };
  },
  props: {
    userInfo: {
      type: Object,
      default: () => ({}),
    },
  },
  computed: {
    statusFormat() {
      return (status) => {
        const statusMap = ["success", "danger", "waring", "info"];
        return statusMap[status] || "";
      };
    },
  },
  created() {
    listSubstation().then((response) => {
      this.substationOptions = response.rows;
    }); // 设备状态列表
    getDeviceStatus().then((response) => {
      this.devStatusOptions = response.data;
    });
    this.getList();
  },
  methods: {
    cancelAuthorize(row) {
      this.$confirm("是否取消当前授权?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          cancelAuthorized({
            userId: this.userInfo.userId,
            deviceId: row.num,
            type: 1,
          }).then((res) => {
            this.$message.success("取消授权成功");
            row.authorizeStatus = "0";
          });
        })
        .catch(() => {});
    },
    handleUserChange() {
      listDeviceAuthorized({ userId: this.userInfo.userId, type: "1" }).then(
        (res) => {
          let authorizationList = res.rows;
          this.authorizedDeviceList.forEach((e) => {
            let obj = authorizationList.find((f) => f.deviceId === e.num);
            this.$set(e, "authorizeStatus", obj ? 1 : 0);
            if (this.userInfo.userName == e.createBy) {
              this.$set(e, "authorizeStatus", 1);
            }
          });
        }
      );
    },
    handleDeleteAuthorize(row, i) {
      this.$refs.deiveAuthorize.toggleRowSelection(row, false);
      //    this.authorizedDeviceList.splice(i,1)
    },
    authorizedDevice() {
      if (!this.userInfo.userId) {
        this.$message.error("请先选择授权用户");
        return;
      }
      if (this.authorizedDeviceList.length === 0) {
        this.$message.error("请选择授权设备信息");
        return;
      }
      this.authorizeOpen = true;
      this.authorizedDeviceList.forEach((e) => {
        this.$set(e, "authorizeStatus", 0);
      });
      this.handleUserChange();
    },
    handleSelectionChange(data) {
      console.log(data);
      this.authorizedDeviceList = data;
    },
    handleExpandChange(row) {
      this.chInfoSourceData = this.devInfoSourceData + row.devInfoSource + "\\";
    },
    handleRowClick(row) {
      this.$refs.deiveAuthorize.toggleRowSelection(row);
    },
    handleRefresh() {
      this.resetForm("queryParamsRef");
      this.getList();
    },
    //查询设备信息
    getList() {
      this.loading = true;
      getDeviceListFold(this.queryParams).then((res) => {
        this.deviceList = res.rows;
        this.deviceOptions = res.rows; //设置下拉框数据；
        this.total = res.total;
        this.loading = false;
        this.$refs.deiveAuthorize.doLayout();
        console.log(this.deviceOptions);
      });
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    submitAuthorizedForm() {
      if (!this.userInfo.userId) {
        this.$message.error("请选择授权用户");
        return;
      }
      if (this.authorizedDeviceList.length === 0) {
        this.$message.error("请选择设备");
        return;
      }
      // if (this.authorizedDeviceList.some(s => s.authorizeStatus == 1)) {
      //     this.$message.error("设置已授权，请删除已授权设备后重新提交")
      //     return
      // }
      let resultList = this.authorizedDeviceList
        .filter((f) => f.authorizeStatus != 1)
        .map((m) => {
          return {
            userId: this.userInfo.userId,
            deviceId: m.num,
            type: 1,
          };
        });
      if (resultList.length === 0) {
        this.$message.error("请添加未授权设备");
        return;
      }
      addDeviceAuthorized(resultList).then((response) => {
        this.$message.success("授权成功");
        this.$refs.deiveAuthorize.clearSelection();
        this.authorizeOpen = false;
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.autocomplete-item-disabled {
  color: #999;
  cursor: not-allowed;
  pointer-events: none;
  /* 禁止点击 */
}

/* 默认隐藏操作列 */
.operation-column {
  visibility: hidden;
}

/* 当鼠标悬停在行上时显示操作列 */
.el-table__row:hover .operation-column {
  visibility: visible;
}

/* 确保按钮在列显示时可见 */
.operation-buttons {
  white-space: nowrap;
}
</style>
